package org.lee.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * SocketGetRequest
 * HTTP的GET请求
 *
 * @author dralee
 * @date 2021-12-28 17:14:49
 **/
public class SocketGetRequest {

    public static void main(String[] args) {
        String domain = "www.haoshuaji.com";
        int port = 80;
        try (Socket socket = new Socket(domain, port)) {
            try (PrintWriter writer = new PrintWriter(socket.getOutputStream())) {
                writer.print("GET / HTTP/1.1\r\n");
                writer.printf("Host: %s\r\n", domain);
                writer.print("Upgrade-Insecure-Requests: 1\r\n");
                writer.print("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36\r\n");
                writer.print("\r\n"); // 空行
                writer.flush();
                socket.shutdownOutput();

                String line;
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                    socket.shutdownInput();
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
